package org.example.spring.carsalemanagementsystem.controller;

import lombok.RequiredArgsConstructor;
import org.example.spring.carsalemanagementsystem.entity.User;
import org.example.spring.carsalemanagementsystem.service.UserService;
import org.example.spring.carsalemanagementsystem.service.impl.UserServiceImpl;
import org.example.spring.carsalemanagementsystem.utils.Result;
import org.example.spring.carsalemanagementsystem.utils.ResultCodeEnum;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Objects;

@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
public class UserController {
    private final UserService userService;
    @PostMapping("/login")
    public Result login(@RequestBody User user) {
        String username = user.getUsername();
        User selectUser = userService.selectByUserName(username);
        if (Objects.isNull(selectUser)){//用户不存在
            return Result.error(ResultCodeEnum.USERNAME_NOT_EXIST);
        }else if (!selectUser.getPassword().equals(user.getPassword())){//密码错误
            return Result.error(ResultCodeEnum.PASSWORD_ERROR);
        }else {
            return Result.success().put(selectUser);
        }
    }
    @PostMapping("/register")
    public Result register(@RequestBody User user){
        String username = user.getUsername();
        User selectUser = userService.selectByUserName(username);
        if (Objects.nonNull(selectUser)){//用户名重复
            return Result.error(ResultCodeEnum.USERNAME_REPEAT);
        }
        userService.insertOne(user);
        return Result.success();
    }
    @PostMapping("/update")
    public Result update(@RequestBody User user){
        userService.updateById(user);
        return Result.success();
    }
}
